<template>
  <el-form
    ref="accountRef"
    :validate-on-rule-change="false"
    :model="accountForm"
    :rules="accountRules"
    class="login-form"
  >
    <el-menu mode="horizontal" default-active="0">
      <el-menu-item index="0"> 忘记密码 </el-menu-item>
    </el-menu>
    <el-form-item></el-form-item>
    <el-form-item prop="phone">
      <el-input
        v-model="accountForm.phone"
        type="text"
        maxlength="11"
        size="large"
        placeholder="手机号"
      >
        <template #prefix>
          <svg-icon icon-class="phone" class="el-input__icon input-icon" />
        </template>
      </el-input>
    </el-form-item>

    <el-form-item prop="smsCode">
      <div class="justify-space-between" style="width: 100%">
        <el-input
          maxlength="6"
          v-model.trim="accountForm.smsCode"
          size="large"
          placeholder="验证码"
          clearable
        >
          <template #prefix>
            <svg-icon icon-class="email" class="el-input__icon input-icon" />
          </template>
        </el-input>
        <el-button plain class="sms-button" @click="getSmsCode" :disabled="disabled">
          {{ btnText }}
        </el-button>
      </div>
    </el-form-item>

    <el-form-item prop="password">
      <el-popover v-model:visible="tipVisible" :width="250" placement="right">
        <template #reference>
          <el-input
            v-model.trim="accountForm.password"
            type="text"
            size="large"
            auto-complete="off"
            placeholder="新密码"
            show-password
            @focus="tipVisible = true"
            @blur="tipVisible = false"
          >
            <template #prefix>
              <svg-icon icon-class="password" class="el-input__icon input-icon" />
            </template>
          </el-input>
        </template>
        <template #default>
          <div :class="['tip-content', { success: pwdTip.pass }]">
            <div>强度：{{ pwdTip.text }}</div>
            <el-progress :percentage="pwdTip.percent" :status="pwdTip.status" />
          </div>
          <div>请至少输入 6 个字符。请不要使用容易被猜到的密码。</div>
        </template>
      </el-popover>
    </el-form-item>

    <el-form-item prop="rePassword">
      <el-input
        v-model="accountForm.rePassword"
        type="password"
        size="large"
        auto-complete="off"
        placeholder="确认新密码"
        show-password
      >
        <template #prefix>
          <svg-icon icon-class="password" class="el-input__icon input-icon" />
        </template>
      </el-input>
    </el-form-item>

    <el-form-item>
      <div class="button-group">
        <el-button size="large" @click.prevent="handleClick(false)"> 取消 </el-button>
        <el-button
          :loading="loading"
          size="large"
          type="primary"
          @click.prevent="handleClick(true)"
        >
          确定
        </el-button>
      </div>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { encrypt } from '@/utils/jsencrypt'
import { ElMessage } from 'element-plus'
import { useCountButton } from '@/hooks/common'
import { formRules } from '@/utils/valid/formRules'
import { sendSmsCode, resetPwd } from '@/api/login'

const emit = defineEmits(['turnBack'])

const { disabled, btnText, startCount } = useCountButton()
const loading = ref(false)
const accountForm = reactive({})
const accountRef = ref(null)
const tipVisible = ref(false)
const accountRules = ref({
  phone: formRules.phone,
  smsCode: formRules.set('请输入收到的验证码'),
  password: [{ validator: validatePass, trigger: 'blur' }],
  rePassword: [{ validator: validatePass2, trigger: 'blur' }]
})
// 密码校验rule
function validatePass(rule, value, callback) {
  if (value === '') {
    callback(new Error('请输入新密码'))
  } else {
    if (accountForm.rePassword !== '') {
      if (!accountRef.value) return
      accountRef.value.validateField('checkPass', () => null)
    }
    if (value && (value.length < 6 || value.length > 16)) {
      return callback(new Error('密码6~16位'))
    }
    callback()
  }
}
function validatePass2(rule, value, callback) {
  if (value === '') {
    callback(new Error('请输入确认新密码'))
  } else if (value !== accountForm.password) {
    callback(new Error('两次密码不一致'))
  } else {
    callback()
  }
}

// 密码强度校验提示
const pwdTip = ref({
  pass: false,
  text: '弱',
  percent: 30,
  status: 'exception'
})
const strengthObj = [
  {
    pass: false,
    text: '弱',
    percent: 30,
    status: 'exception'
  },
  {
    pass: true,
    text: '安全',
    percent: 80,
    status: 'success'
  },
  {
    pass: true,
    text: '强',
    percent: 100,
    status: 'success'
  }
]

watchEffect(() => {
  const level = formRules.getPwdStrength(accountForm.password)
  pwdTip.value = strengthObj[level - 1]
})

//短信
function getSmsCode() {
  accountRef.value.validateField('phone', (valid) => {
    if (valid) {
      startCount()
      sendSmsCode(accountForm.phone)
    }
  })
}

function handleClick(action) {
  if (action) {
    accountRef.value.validate((valid) => {
      if (valid) {
        loading.value = true

        const data = { ...accountForm }
        if (data.password) data.password = encrypt(data.password)
        if (data.rePassword) data.rePassword = encrypt(data.rePassword)

        resetPwd(data)
          .then(() => {
            ElMessage.success('密码重置成功')
            setTimeout(() => {
              handleClick(false)
            }, 300)
          })
          .finally(() => {
            loading.value = false
          })
      }
    })
  } else {
    accountRef.value.resetFields()
    emit('turnBack')
  }
}
</script>

<style lang="scss" scoped>
.el-menu {
  border-bottom: none;
  .el-menu-item {
    font-size: 16px;
  }
}
.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  min-width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 40px;
    input {
      height: 40px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
  .sms-button {
    width: 7em;
    height: 40px;
    margin-left: 1em;
  }
  .button-group {
    margin-top: 30px;
    width: 100%;
    display: flex;
    justify-content: space-around;
    .el-button {
      width: 40%;
    }
  }
}
.tip-content {
  color: var(--el-color-danger);
}
.el-progress {
  width: 250px;
  margin: 5px 0;
}
.success {
  color: var(--el-color-success);
}
</style>
